package com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.sample;

import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.constant.VoiceRecognitionConstant;
import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.model.BusinessParam;
import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.service.VoiceRecognitionService;
import com.eduagent.xwqeduagent.api.InstantVoiceToTextConversion.service.VoiceRecognitionService.RecognitionCallback;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.concurrent.CountDownLatch;

/**
 * 语音识别API示例程序
 */
public class VoiceRecognitionDemo {
    
    // 设置讯飞开放平台的API凭证
    private static final String APP_ID = "637d1630";
    private static final String API_KEY = "8bd0514cb66802c719bbf34a908a0119";
    private static final String API_SECRET = "NzUyY2Y3OTYwYjAyMGExODc5OTM1ZGZl";
    
    public static void main(String[] args) {
        try {
            // 初始化API凭证
            VoiceRecognitionConstant.APP_ID = APP_ID;
            VoiceRecognitionConstant.API_KEY = API_KEY;
            VoiceRecognitionConstant.API_SECRET = API_SECRET;
            
            // 创建服务实例
            VoiceRecognitionService service = new VoiceRecognitionService();
            
            // 执行同步识别示例
            System.out.println("===== 同步识别示例 =====");
            syncRecognitionDemo(service);
            
            // 执行异步识别示例
            System.out.println("\n===== 异步识别示例 =====");
            asyncRecognitionDemo(service);
            
        } catch (Exception e) {
            System.err.println("示例运行失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 同步识别示例
     * 
     * @param service 语音识别服务
     * @throws Exception 识别过程中的异常
     */
    private static void syncRecognitionDemo(VoiceRecognitionService service) throws Exception {
        // 读取音频文件（假设在resources目录下有一个16k采样率的PCM音频文件）
        String audioFilePath = "src/main/resources/iat/16k_10.pcm";
        byte[] audioData = readAudioFile(audioFilePath);
        
        if (audioData == null) {
            System.err.println("未找到音频文件: " + audioFilePath);
            System.err.println("请准备一个16k采样率的PCM音频文件进行测试");
            return;
        }
        
        // 设置业务参数
        BusinessParam businessParam = BusinessParam.builder()
                .language(VoiceRecognitionConstant.LANGUAGE_CHINESE)
                .domain(VoiceRecognitionConstant.DOMAIN_COMMON)
                .accent(VoiceRecognitionConstant.ACCENT_MANDARIN)
                .ptt(1) // 启用标点符号
                .build();
        
        System.out.println("开始识别音频...");
        long startTime = System.currentTimeMillis();
        
        // 执行同步识别
        String result = service.recognizeSpeech(audioData, businessParam);
        
        long endTime = System.currentTimeMillis();
        System.out.println("识别完成，耗时: " + (endTime - startTime) + "ms");
        System.out.println("识别结果: " + result);
    }
    
    /**
     * 异步识别示例
     * 
     * @param service 语音识别服务
     * @throws Exception 识别过程中的异常
     */
    private static void asyncRecognitionDemo(VoiceRecognitionService service) throws Exception {
        // 读取音频文件（假设在resources目录下有一个16k采样率的PCM音频文件）
        String audioFilePath = "src/main/resources/iat/16k_10.pcm";
        byte[] audioData = readAudioFile(audioFilePath);
        
        if (audioData == null) {
            System.err.println("未找到音频文件: " + audioFilePath);
            System.err.println("请准备一个16k采样率的PCM音频文件进行测试");
            return;
        }
        
        // 设置业务参数（开启动态修正）
        BusinessParam businessParam = BusinessParam.builder()
                .language(VoiceRecognitionConstant.LANGUAGE_CHINESE)
                .domain(VoiceRecognitionConstant.DOMAIN_COMMON)
                .accent(VoiceRecognitionConstant.ACCENT_MANDARIN)
                .ptt(1) // 启用标点符号
                .dwa("wpgs") // 开启动态修正
                .build();
        
        System.out.println("开始异步识别音频...");
        long startTime = System.currentTimeMillis();
        
        // 用于等待异步识别完成
        CountDownLatch latch = new CountDownLatch(1);
        
        // 创建回调
        RecognitionCallback callback = new RecognitionCallback() {
            @Override
            public void onSuccess(String result) {
                long endTime = System.currentTimeMillis();
                System.out.println("识别完成，耗时: " + (endTime - startTime) + "ms");
                System.out.println("最终识别结果: " + result);
                latch.countDown();
            }
            
            @Override
            public void onError(int errorCode, String errorMessage) {
                System.err.println("识别失败: " + errorMessage + ", 错误码: " + errorCode);
                latch.countDown();
            }
            
            @Override
            public void onPartialResult(String result, boolean isLast) {
                System.out.println("实时识别结果: " + result + (isLast ? " (最后一个结果)" : ""));
            }
        };
        
        // 执行异步识别
        service.recognizeSpeechAsync(audioData, businessParam, callback);
        
        // 等待异步识别完成
        latch.await();
    }
    
    /**
     * 读取音频文件
     * 
     * @param filePath 文件路径
     * @return 音频数据
     */
    private static byte[] readAudioFile(String filePath) {
        try {
            File audioFile = new File(filePath);
            
            if (!audioFile.exists()) {
                return null;
            }
            
            return Files.readAllBytes(Paths.get(filePath));
            
        } catch (IOException e) {
            System.err.println("读取音频文件失败: " + e.getMessage());
            return null;
        }
    }
} 